/**
 * 编辑企业--js
 * @author xiangfei
 * @date 2019年3月27日
 */
var enterprise_edit = {
    data : {
        id : "", // 企业id
        obj : {}, // 企业对象
        // 企业需求统一放在这里，urgent是紧急  commonly是一般
        entNeeds : []
    },
    /**
     * 初始化，包括初始化日期选择器，保存id，获取企业对象
     */
    init : function() {
        enterprise_edit.initDatePicker();
        enterprise_edit.getAllIndustryParent();
        var obj = GetRequest();
        enterprise_edit.data.id = obj.id;
        enterprise_edit.getDetail(enterprise_edit.data.id);
    },
    /**
     * 日期选择器初始化
     */
    initDatePicker : function() {
        laydate.render({
            elem: '#entOneBirthday' //生日1
        });
        laydate.render({
            elem: '#entTwoBirthday' //生日2
        });
    },
    /**
     * 获取所有行业大类供选择
     */
    getAllIndustryParent : function() {
        $.ajax({
            url : "/crm/industry/findAllParent",
            dataType : "json",
            type : "get",
            success : function(res) {
                if(res.length > 0) {
                    enterprise_edit.data.industry = res;
                    var industryOptions = "";
                    for(var i = 0 ; i < res.length ; i ++) {
                        industryOptions += '<option value="' + res[i].uuid + '">'+res[i].indName+'</option>'
                    }
                    $("#entIndustryOne").append(industryOptions);
                }
            },
            error : function() {
                layer.alert("获取行业信息错误！", {icon: 2, closeBtn: 0 }, function(index) {
                    layer.close(index);
                });
            }
        });
    },
    /**
     * 获取企业详情
     * @param id 企业id
     */
    getDetail : function(id) {
        $.ajax({
            url : "/crm/enterprise/get",
            dataType : "json",
            data : {
                id:id
            },
            type : "get",
            success : function(res) {
                if(res && res.id) {
                    enterprise_edit.data.obj = res;
                    $("#entName").val(res.entName);
                    $("#entAddress").val(res.entAddress);
                    $("#entOnePerson").val(res.entOnePerson);
                    $("#entOnePhone").val(res.entOnePhone);
                    $("#entOneBirthday").val(res.entOneBirthday);
                    $("#entTwoPerson").val(res.entTwoPerson);
                    $("#entTwoPhone").val(res.entTwoPhone);
                    $("#entTwoBirthday").val(res.entTwoBirthday);
                    // 行业大类的处理
                    if(!isBlank(res.entIndustryOne)) {
                        try {
                            var industryOne = JSON.parse(res.entIndustryOne);
                            $("#entIndustryOne").val(industryOne.uuid);
                        } catch(e) {
                            console.log("转换行业大类失败");
                            console.log(e);
                        }
                    }
                    $("#entIndustryTwo").val(res.entIndustryTwo);
                    $("#entUpstream").val(res.entUpstream);
                    $("#entDownstream").val(res.entDownstream);
                    $("#entStockRight").val(res.entStockRight);
                    $("#entProduct").val(res.entProduct);
                    $("#entMode").val(res.entMode);

                    var indexId = 0;
                    // 转换紧急需求
                    if(res.entNeedsUrgent && res.entNeedsUrgent !== "" && res.entNeedsUrgent !== '[""]') {
                        try {
                            var needUrgentTemp = JSON.parse(res.entNeedsUrgent);
                            if(needUrgentTemp && needUrgentTemp.length > 0) {
                                for(var i = 0 ; i < needUrgentTemp.length ; i ++) {
                                    enterprise_edit.data.entNeeds.push({
                                        id : "need_id_" + indexId,
                                        text : needUrgentTemp[i],
                                        degree : "urgent"
                                    });
                                    indexId ++;
                                }
                            } else {
                                enterprise_edit.data.entNeeds.push({
                                    id : "need_id_" + indexId,
                                    text : "",
                                    degree : "urgent"
                                });
                                indexId ++;
                            }
                        } catch (e) {
                            console.log("enterprise_edit.js:转换紧急需求json失败");
                            console.log(e);
                        }
                    }
                    // 转换一般需求
                    if(res.entNeedsCommonly && res.entNeedsCommonly !== "" && res.entNeedsCommonly !== '[""]') {
                        try {
                            var needCommonlyTemp = JSON.parse(res.entNeedsCommonly);
                            if(needCommonlyTemp && needCommonlyTemp.length > 0) {
                                for(var j = 0 ; j < needCommonlyTemp.length ; j ++) {
                                    enterprise_edit.data.entNeeds.push({
                                        id : "need_id_" + indexId,
                                        text : needCommonlyTemp[j],
                                        degree : "commonly"
                                    });
                                    indexId ++;
                                }
                            } else {
                                enterprise_edit.data.entNeeds.push({
                                    id : "need_id_" + indexId,
                                    text : "",
                                    degree : "commonly"
                                });
                            }
                        } catch (e) {
                            console.log("enterprise_edit.js:转换紧一般需求json失败");
                            console.log(e);
                        }
                    }
                    enterprise_edit.initNeeds();
                    // 初始化相关联数据
                    ent_associated_edit.initAfterEnt(enterprise_edit.data.obj);
                }
            },
            error : function() {
                layer.msg("系统错误！", {icon: 2,closeBtn: 0});
            }
        });
    },
    /**
     * 获取页面上所有的企业需求，并赋值编好顺序的id，返回对象数组给调用者
     * @returns {Array}
     */
    getAllNeeds : function(){
        var length = $(".needs").length;
        var needs = [];
        for(var i = 0 ; i < length ; i ++) {
            needs.push({
                id : "need_id_" + i,
                text : $(".needs input")[i].value,
                degree : $(".needs select")[i].value
            });
        }
        return needs;
    },
    /**
     * 渲染需求列表,拼接好后先移除旧的，再添加渲染好的
     */
    initNeeds : function() {
        var html = "";
        for(var i = 0 ; i < enterprise_edit.data.entNeeds.length ; i ++) {
            html +=
                '<div class="cr_tj needs" id="need_tr_'+i+'">'+
                    '<dl>'+
                        '<dt class="'+(i===0?"":"no_label")+'" id="need_title_'+i+'">'+(i === 0 ? "企业需求：" : "")+'</dt>'+
                        '<dd>'+
                            '<input type="text" id="need_text_'+i+'" value="'+enterprise_edit.data.entNeeds[i].text+'">'+
                            '<select id="need_degree_'+i+'">'+
                                '<option value="urgent" '+(enterprise_edit.data.entNeeds[i].degree === "urgent" ? "selected" : "")+'>紧急</option>'+
                                '<option value="commonly" '+(enterprise_edit.data.entNeeds[i].degree === "commonly" ? "selected" : "")+'>一般</option>'+
                            '</select>'+
                            '<button class="btn_add" onclick="enterprise_edit.addNeed()">添加</button>'+
                            '<button class="btn_del" onclick="enterprise_edit.deleteNeed(\'need_id_'+i+'\')">删除</button>'+
                        '</dd>'+
                    '</dl>'+
                '</div>'
        }
        $(".needs").remove();
        $("#operation").before(html);
    },
    /**
     * 刷新企业需求列表，一般发生在删除需求后
     */
    refreshNeeds : function() {
        enterprise_edit.data.entNeeds = enterprise_edit.getAllNeeds(); // 获取页面上现有的需求，
        enterprise_edit.initNeeds();
    },
    /**
     * 添加需求，默认紧急
     */
    addNeed : function() {
        var i = enterprise_edit.data.entNeeds.length;
        var html =
            '<div class="cr_tj needs" id="need_tr_'+i+'">'+
                '<dl>'+
                    '<dt class="no_label" id="need_title_'+i+'"></dt>'+
                    '<dd>'+
                        '<input type="text" id="need_text_'+i+'">'+
                        '<select id="need_degree_'+i+'">'+
                            '<option value="urgent">紧急</option>'+
                            '<option value="commonly">一般</option>'+
                        '</select>'+
                        '<button class="btn_add" onclick="enterprise_edit.addNeed()">添加</button>'+
                        '<button class="btn_del" onclick="enterprise_edit.deleteNeed(\'need_id_'+i+'\')">删除</button>'+
                    '</dd>'+
                '</dl>'+
            '</div>';
        $("#operation").before(html);
        enterprise_edit.data.entNeeds.push({
            id : "need_id_" + i,
            text : "",
            degree : "urgent"
        });
    },
    /**
     * 删除需求，需要传入id
     * @param id DOM上按钮渲染的id
     */
    deleteNeed : function(id) {
        if(enterprise_edit.data.entNeeds.length > 2) {
            $("#need_tr_"+id.slice(id.lastIndexOf("_")+1,id.length)).remove();
            for(var i = 0 ; i < enterprise_edit.data.entNeeds.length ; i ++) {
                if(id === enterprise_edit.data.entNeeds[i].id) {
                    enterprise_edit.data.entNeeds.splice(i,1);
                }
            }
            enterprise_edit.refreshNeeds();
        } else {
            layer.msg("最少保留两个需求");
        }
    },
    /**
     * 保存编辑的企业
     */
    editSave : function(_this) {
        var that = _this;
        var entName = $("#entName").val();
        var entAddress = $("#entAddress").val();
        var entOnePerson = $("#entOnePerson").val();
        var entOnePhone = $("#entOnePhone").val();
        var entOneBirthday = $("#entOneBirthday").val();
        var entTwoPerson = $("#entTwoPerson").val();
        var entTwoPhone = $("#entTwoPhone").val();
        var entTwoBirthday = $("#entTwoBirthday").val();
        var entIndustryOne = $("#entIndustryOne").val();
        var entIndustryTwo = $("#entIndustryTwo").val();
        var entUpstream = $("#entUpstream").val();
        var entDownstream = $("#entDownstream").val();
        var entStockRight = $("#entStockRight").val();
        var entProduct = $("#entProduct").val();
        var entMode = $("#entMode").val();


        if(enterprise_edit.isBlank(entName)) {
            layer.msg("请输入名称");
            return false;
        }
        if(enterprise_edit.isBlank(entAddress)) {
            layer.msg("请输入地址");
            return false;
        }
        if(enterprise_edit.isBlank(entOnePerson)) {
            layer.msg("请输入联系人1姓名");
            return false;
        }

        if(!enterprise_edit.phoneAvailable(entOnePhone)) {
            layer.msg("请正确输入电话号码");
            return false;
        }


        enterprise_edit.data.obj.entName = entName;
        enterprise_edit.data.obj.entAddress = entAddress;
        enterprise_edit.data.obj.entOnePerson = entOnePerson;
        enterprise_edit.data.obj.entOnePhone = entOnePhone;
        enterprise_edit.data.obj.entOneBirthday = entOneBirthday;
        enterprise_edit.data.obj.entTwoPerson = entTwoPerson;
        enterprise_edit.data.obj.entTwoPhone = entTwoPhone;
        enterprise_edit.data.obj.entTwoBirthday = entTwoBirthday;
        /**
         * 行业大类的处理
         * @type {*|jQuery}
         */
        if(entIndustryOne && !isBlank(entIndustryOne)) {
            for(var j = 0 ; j < enterprise_edit.data.industry.length ; j ++) {
                if(enterprise_edit.data.industry[j].uuid === entIndustryOne) {
                    enterprise_edit.data.obj.entIndustryOne = JSON.stringify(enterprise_edit.data.industry[j]);
                }
            }
        } else {
            enterprise_edit.data.obj.entIndustryOne = null;
        }
        enterprise_edit.data.obj.entIndustryTwo = entIndustryTwo;
        enterprise_edit.data.obj.entUpstream = entUpstream;
        enterprise_edit.data.obj.entDownstream = entDownstream;
        enterprise_edit.data.obj.entStockRight = entStockRight;
        enterprise_edit.data.obj.entProduct = entProduct;
        enterprise_edit.data.obj.entMode = entMode;
        /**
         * 需求的处理
         * @type {*|jQuery}
         */
        var entNeedsUrgent = [];
        var entNeedsCommonly = [];
        var needs = enterprise_edit.getAllNeeds();
        for(var i = 0 ; i < needs.length ; i ++) {
            if(!enterprise_edit.isBlank(needs[i].text)) {
                if(needs[i].degree === "urgent") {
                    entNeedsUrgent.push(needs[i].text);
                } else if (needs[i].degree === "commonly") {
                    entNeedsCommonly.push(needs[i].text);
                }
            }
        }
        enterprise_edit.data.obj.entNeedsUrgent = JSON.stringify(entNeedsUrgent);
        enterprise_edit.data.obj.entNeedsCommonly = JSON.stringify(entNeedsCommonly);

        // 准备保存
        $(_this).attr("onclick","");
        $(_this).css("background","#c0c1c0");
        $.ajax({
            url : "/crm/enterprise/save",
            dataType : "json",
            data : enterprise_edit.data.obj,
            type : "post",
            success : function(data) {
                if(data.status) {
                	parent.refreshTabByIndex(0);
                	 // 初始化相关联数据
                	enterprise_edit.data.obj = data.obj;
                    ent_associated_edit.initAfterEnt(data.obj);
                    layer.alert(data.info, {icon: 1, closeBtn: 0}, function(index) {
                        // parent.closeCurPage();
                        layer.close(index);
                    });
                } else {
                    layer.alert(data.info, {icon: 2, closeBtn: 0}, function(index) {
                        $(that).attr("onclick","enterprise_edit.editSave(this)");
                        $(that).css("background","#d53638");
                        layer.close(index);
                    });
                }
            },
            error : function() {
                layer.alert("系统错误！", {icon: 2, closeBtn: 0 },function(index) {
                    $(_this).attr("onclick","enterprise_edit.editSave(this)");
                    $(_this).css("background","#d53638");
                    layer.close(index);
                });
            }
        });
    },
    /**
     * 重置企业编辑的所有输入
     * @param _this
     */
    reset : function(_this) {
        var _that = _this;
        layer.confirm("确定重置吗?所有更改将失效.", {icon: 3, title:'请确认'}, function (layer_index) {
            $("#entName").val(enterprise_edit.data.obj.entName);
            $("#entAddress").val(enterprise_edit.data.obj.entAddress);
            $("#entOnePerson").val(enterprise_edit.data.obj.entOnePerson);
            $("#entOnePhone").val(enterprise_edit.data.obj.entOnePhone);
            $("#entOneBirthday").val(enterprise_edit.data.obj.entOneBirthday);
            $("#entTwoPerson").val(enterprise_edit.data.obj.entTwoPerson);
            $("#entTwoPhone").val(enterprise_edit.data.obj.entTwoPhone);
            $("#entTwoBirthday").val(enterprise_edit.data.obj.entTwoBirthday);
            $("#entIndustryOne").val(enterprise_edit.data.obj.entIndustryOne);
            $("#entIndustryTwo").val(enterprise_edit.data.obj.entIndustryTwo);
            $("#entUpstream").val(enterprise_edit.data.obj.entUpstream);
            $("#entDownstream").val(enterprise_edit.data.obj.entDownstream);
            $("#entStockRight").val(enterprise_edit.data.obj.entStockRight);
            $("#entProduct").val(enterprise_edit.data.obj.entProduct);
            $("#entMode").val(enterprise_edit.data.obj.entMode);

            var indexReset = 0;
            enterprise_edit.data.entNeeds = [];
            // 转换紧急需求
            if(enterprise_edit.data.obj.entNeedsUrgent && enterprise_edit.data.obj.entNeedsUrgent !== "" && enterprise_edit.data.obj.entNeedsUrgent !== '[""]') {
                try {
                    var needUrgentTemp = JSON.parse(enterprise_edit.data.obj.entNeedsUrgent);
                    if(needUrgentTemp && needUrgentTemp.length > 0) {
                        for(var i = 0 ; i < needUrgentTemp.length ; i ++) {
                            enterprise_edit.data.entNeeds.push({
                                id : "need_id_" + indexReset,
                                text : needUrgentTemp[i],
                                degree : "urgent"
                            });
                            indexReset ++;
                        }
                    }
                } catch (e) {
                    console.log("enterprise_edit.js:转换紧急需求json失败");
                    console.log(e);
                }
            }
            // 转换一般需求
            if(enterprise_edit.data.obj.entNeedsCommonly && enterprise_edit.data.obj.entNeedsCommonly !== "" && enterprise_edit.data.obj.entNeedsCommonly !== '[""]') {
                try {
                    var needCommonlyTemp = JSON.parse(enterprise_edit.data.obj.entNeedsCommonly);
                    if(needCommonlyTemp && needCommonlyTemp.length > 0) {
                        for(var j = 0 ; j < needCommonlyTemp.length ; j ++) {
                            enterprise_edit.data.entNeeds.push({
                                id : "need_id_" + indexReset,
                                text : needCommonlyTemp[j],
                                degree : "commonly"
                            });
                            indexReset ++;
                        }
                    }
                } catch (e) {
                    console.log("enterprise_edit.js:转换紧一般需求json失败");
                    console.log(e);
                }
            }
            enterprise_edit.initNeeds();
            layer.close(layer_index);
        });

    },
    /**
     * 校验手机号码是否合法
     * @param phone 电话号码
     * @returns {boolean} 合法返回true,否则false
     */
    phoneAvailable : function (phone) {
        var reg = /^[1][3,4,5,7,8][0-9]{9}$/;
        return reg.test(phone);
    },
    /**
     * 判断字符串是否空值
     * @param str 传入参数
     * @returns {boolean} 空返回true,空false
     */
    isBlank : function (str) {
        return (typeof str === "undefined" || str === "undefined" || str === null || str === "null" || str === "" || str.length <= 0);
    }
};